import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/login/login_router.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/net/base_entity.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/setting/iview/account_iview.dart';
import 'package:flutter_deer/setting/presenter/account_presenter.dart';
import 'package:flutter_deer/shop/models/user_entity.dart';
import 'package:flutter_deer/shop/provider/user_provider.dart';
import 'package:flutter_deer/util/device_utils.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/click_item.dart';
import 'package:flutter_deer/widgets/iview/file_upload_iview.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/presenter/file_upload_presenter.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_deer/widgets/text_field_item.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';
import 'package:http_parser/src/media_type.dart';

class AccountManagerPage extends StatefulWidget {

  const AccountManagerPage({super.key});

  @override
  _AccountManagerPageState createState() => _AccountManagerPageState();
}

class _AccountManagerPageState extends State<AccountManagerPage> with BasePageMixin<AccountManagerPage, PowerPresenter> implements AccountIMvpView,FileUploadIMvpView{

  UserProvider provider = UserProvider();
  late AccountPagePresenter accountPagePresenter;
  late FileUploadPagePresenter fileUploadPagePresenter;
  TextEditingController _nicknameController = TextEditingController();

  @override
  void uploadResult(FileUploadEntity? uploadResult){
    if(uploadResult!.url.nullSafe.isNotEmpty){
      SpUtil.putString(Constant.tempUserAvatarUrl, uploadResult!.url.nullSafe);
      accountPagePresenter.updateAvatar(uploadResult!.url.nullSafe);
    }
  }

  @override
  void uploadAvatarResult(bool? result){
    if(result==true){
      provider.setUserAvatar(SpUtil.getString(Constant.tempUserAvatarUrl));
    }
  }

  @override
  void setUpdateNicknameResult(bool? result){
    if(result==true) {
      accountPagePresenter.getCurrentUserInfo();
      NavigatorUtils.goBack(context);
      showToast('${DeerLocalizations.of(context)!.nicknameUpdateSuccess.nullSafe}');
    }else{
      showToast('${DeerLocalizations.of(context)!.nicknameUpdateFail.nullSafe}');
    }
  }

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    accountPagePresenter = new AccountPagePresenter();
    fileUploadPagePresenter = new FileUploadPagePresenter();
    powerPresenter.requestPresenter([accountPagePresenter,fileUploadPagePresenter]);
    return powerPresenter;
  }

  final ImagePicker _picker = ImagePicker();
  ImageProvider? _imageProvider;
  XFile? pickedFile;

  @override
  void setUser(UserInfoEntity? user) {
    provider.setUser(user);
  }

  Future<void> _getImage() async {
    try {
        pickedFile = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 800);
        if (pickedFile != null) {
          if(Device.isWeb){
            Uint8List list = await pickedFile!.readAsBytes();
            MultipartFile multipartFile = MultipartFile.fromBytes(list.toList(),
              filename: pickedFile!.name,
              contentType: MediaType('image', 'jpg'),
            );
            fileUploadPagePresenter.uploadWebFile(multipartFile);
          }else {
            _imageProvider = FileImage(File(pickedFile!.path));
            fileUploadPagePresenter.uploadFile(
                pickedFile!.path, pickedFile!.mimeType.nullSafe);
          }
        } else {
          _imageProvider = null;
        }
      setState(() {

      });
    } catch (e) {
      if (e is MissingPluginException) {
        showToast('${DeerLocalizations.of(context)!.platformNotSupported.nullSafe}');
      } else {
        print(e);
        showToast('${DeerLocalizations.of(context)!.noPhotoAlbumPermissions.nullSafe}');
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<UserProvider>(
      create: (_) => provider,
      child:Scaffold(
        appBar: MyAppBar(
          centerTitle: '${DeerLocalizations.of(context)!.accountManagement.nullSafe}',
        ),
        body: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                ClickItem(
                  title: '${DeerLocalizations.of(context)!.playerAvatar.nullSafe}',
                  onTap: () {
                    _getImage();
                  }
                ),
                Positioned(
                  top: 8.0,
                  bottom: 8.0,
                  right: 40.0,
                  child: Consumer<UserProvider>(
                    builder: (_, provider, child) {
                      if(provider.stateType==StateType.loading){
                        return LoadingAnimationWidget.dotsTriangle(
                          color: context.isDark ? Colors.white : Colours.dark_app_main,
                          size: 19,
                        );
                      }
                      return CircleAvatar(
                          radius: 38.0,
                          backgroundColor: Colors.transparent,
                          backgroundImage: ImageUtils.getImageProvider(Constant.imageServerHost+'${provider.user!.sysUser!.avatar}', holderImg: 'shop/tx')
                      );
                    }
                  )
                )
              ],
            ),
            ClickItem(
                title: '${DeerLocalizations.of(context)!.changePassword.nullSafe}',
                content: '${DeerLocalizations.of(context)!.changePasswordTip.nullSafe}',
                onTap: () => NavigatorUtils.push(context, LoginRouter.updatePasswordPage,arguments: provider.user!.sysUser!.accountId.nullSafe)
            ),
            Consumer<UserProvider>(
                builder: (_, provider, child) {
                  if(provider.stateType==StateType.loading){
                    return ClickItem(title:'${DeerLocalizations.of(context)!.changeNickname.nullSafe}',content: '${DeerLocalizations.of(context)!.changeNicknameTip.nullSafe}',);
                  }
                  return ClickItem(
                      title: '${DeerLocalizations.of(context)!.changeNickname.nullSafe}',
                      content: provider.nickname!,
                      onTap: (){
                        _nicknameController.text = provider.nickname!;
                        _showCustomModalBottomSheet();
                      }
                  );
                }),
            Consumer<UserProvider>(
                builder: (_, provider, child) {
                  return ClickItem(
                    title: '${DeerLocalizations.of(context)!.myMobile.nullSafe}',
                    content: provider.stateType==StateType.loading?'':provider.user!.sysUser!.phone.nullSafe,
                  );
                }
            ),
            Consumer<UserProvider>(
              builder: (_, provider, child) {
                return ClickItem(
                  title: '${DeerLocalizations.of(context)!.playerAccount.nullSafe}',
                  content: provider.stateType==StateType.loading?'':provider.user!.sysUser!.accountId.nullSafe,
                );
              }
            ),
            Consumer<UserProvider>(
                builder: (_, provider, child) {
                  return ClickItem(
                    title: '${DeerLocalizations.of(context)!.myPromotionCode.nullSafe}',
                    content: provider.stateType==StateType.loading?'':provider.user!.sysUser!.shareCode.nullSafe,
                  );
                }
            )
          ],
        ),
      )
    );
  }

  Future<dynamic> _showCustomModalBottomSheet() async {
    showDialog<void>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10.0),
            ),
            backgroundColor: context.isDark?Colours.dark_bg_color:Colours.bg_color,
            title: Text('${DeerLocalizations.of(context)!.changeNickname.nullSafe}',style: TextStyle(color: context.isDark?Colours.dark_text:Colours.text),),
            content:  Container(
              width: MediaQuery.of(context).size.width-20,
              child: TextFieldItem(
                controller: _nicknameController,
                title: '${DeerLocalizations.of(context)!.playerNickname.nullSafe}',
                hintText: '${DeerLocalizations.of(context)!.playerNicknameTip.nullSafe}',
              ),
            ),
            actions: <Widget>[
              TextButton(
                onPressed: () => NavigatorUtils.goBack(context),
                child: Text('${DeerLocalizations.of(context)!.cancel.nullSafe}'),
              ),
              TextButton(
                onPressed: () {
                  if(_nicknameController.text.trim().nullSafe==''){

                  }else {
                    accountPagePresenter.updateNickname(_nicknameController.text
                        .trim()
                        .nullSafe);
                  }
                },
                child: Text('${DeerLocalizations.of(context)!.ok.nullSafe}'),
              ),
            ],
          );
        }
    );
  }
}
